package com.ruoyi.framework.weChat.social;


import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.project.system.domain.SocialUserconnection;
import com.ruoyi.project.system.domain.SysSocial;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISocialUserconnectionService;
import com.ruoyi.project.system.service.ISysSocialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * @Classname SocialRedisHelper
 * @Description 将第三方用户信息保存到redis里面
 * @Author h21448
 * @Date 2020-04-02 09:48
 * @Version 1.0
 */
@Component
public class SocialRedisHelper {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private UsersConnectionRepository usersConnectionRepository;

    @Autowired
    private ConnectionFactoryLocator connectionFactoryLocator;

    @Autowired
    private ISocialUserconnectionService socialService;

    /**
     * 缓存第三方用户信息
     * @param mkey
     * @param connectionData
     */
    public void saveConnectionData(String mkey, BaseConnectionData connectionData) {
        redisTemplate.opsForValue().set(getKey(mkey), connectionData, 10, TimeUnit.MINUTES);
    }

    /**
     *
     * @param mkey
     * @param userId
     */
    public void saveStateUserId(String mkey, String userId) {
        redisTemplate.opsForValue().set(getKey(mkey), userId, 10, TimeUnit.MINUTES);
    }

    /**
     *
     * @param mkey
     * @return
     */
    public String getStateUserId(String mkey) {
        String key = getKey(mkey);
        if (!redisTemplate.hasKey(key)) {
            throw new RuntimeException("无法找到缓存的第三方社交账号信息");
        }
        return (String) redisTemplate.opsForValue().get(key);
    }


    /**
     * 第三方社交账号信息进行与业务系统账号绑定
     * @param mkey
     * @param userId
     */
    public void doPostSignUp(String mkey, Long userId) {
        String key = getKey(mkey);
        if (!redisTemplate.hasKey(key)) {
            throw new RuntimeException("无法找到缓存的第三方社交账号信息");
        }
        BaseConnectionData preConnectionData = (BaseConnectionData) redisTemplate.opsForValue().get(key);
        ConnectionData connectionData = null;
        if (preConnectionData != null) {
            connectionData = new ConnectionData(preConnectionData.getProviderId(),preConnectionData.getProviderUserId(),preConnectionData.getDisplayName(),preConnectionData.getProfileUrl(),preConnectionData.getImageUrl(),preConnectionData.getAccessToken(),preConnectionData.getSecret(),preConnectionData.getRefreshToken(),preConnectionData.getExpireTime());
        }
        Connection<?> connection = connectionFactoryLocator.getConnectionFactory(preConnectionData.getProviderId())
                .createConnection(connectionData);
        usersConnectionRepository.createConnectionRepository(String.valueOf(userId)).addConnection(connection);
        redisTemplate.delete(key);
    }

    public boolean doSignUp(String mkey, SysUser sysUser) {
        String key = getKey(mkey);
        if (!redisTemplate.hasKey(key)) {
            throw new RuntimeException("无法找到缓存的第三方社交账号信息");
        }
        BaseConnectionData preConnectionData = (BaseConnectionData) redisTemplate.opsForValue().get(key);
        SocialUserconnection sysSocial =new SocialUserconnection ();
        BeanUtil.copyProperties(preConnectionData,sysSocial);
        sysSocial.setRank(1l);
        sysSocial.setUserid(String.valueOf(sysUser.getUserId()));
        sysSocial.setTenantId(sysUser.getTenantId());
        boolean flag=false;
        try {
            int n = socialService.insertSocialUserconnection(sysSocial);
            if (n >0) {
                flag=true;
            }
        } catch (Exception e) {
            throw new CustomException("该账号已被其他社交账号绑定",2001);
        }
       return flag;

    }

    /**
     * 第三方社交账号信息进行与业务系统账号解绑
     * @param userId
     */
    public void doPostSignDown(Integer userId,String providerId) {
        usersConnectionRepository.createConnectionRepository(String.valueOf(userId)).removeConnections(providerId);
    }


    private String getKey(String key) {
        if (StringUtils.isEmpty(key)) {
            throw new RuntimeException("key不为空");
        }
        return "pre:security:social.connect." + key;
    }
}
